package com.chat.room;

import com.chat.room.client.ChatRoomClient;
import com.chat.room.client.ServiceSearch;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.concurrent.CountDownLatch;

@Slf4j
public class ClientRun {

    public static final CountDownLatch COUNT_DOWN_LATCH = new CountDownLatch(1);

    public static void main(String[] args) throws SocketException {
        int port = 31007;
        ServiceSearch serviceSearch = new ServiceSearch(new DatagramSocket(port),port);
        serviceSearch.listener();
        try {
            serviceSearch.searchSend();
        } catch (IOException e) {
            log.error("广播发送异常:{}",e);
        }

        while (serviceSearch.getServerInfoList().isEmpty()) {}
        serviceSearch.close();
        ChatRoomClient chatRoomClient = new ChatRoomClient(serviceSearch.getServerInfoList().get(0));
        chatRoomClient.start();
        try {
            COUNT_DOWN_LATCH.await();
        } catch (InterruptedException e) {
            log.error("线程被中断:{}",e);
            Thread.currentThread().interrupt();
        } finally {
            chatRoomClient.shutdown();
        }
    }
}